import Vue from "vue";
import Vuex from "vuex";
import $api from "../common/api";
Vue.use(Vuex);
const store = new Vuex.Store({
  state: {
    shareId: '',
    userInfo: {},
    loginInfo: {},
    token: "",
    commonCity: {
      id: 11,
      name: "无锡",
      slug: "wx",
    },
  },
  getters: {
    isLogin(state) {
      return state.userInfo.nick_name && state.userInfo.mobile;
    },
  },
  mutations: {
    changShareId(state, provider) {
      state.shareId = provider;
    },
    changToken(state, provider) {
      state.token = provider;
      uni.setStorageSync("TOKEN", state.token);
    },
    changCommonCity(state, provider) {
      state.commonCity = Object.assign({}, state.commonCity, provider);
    },
    changUserInfo(state, provider) {
      state.userInfo = Object.assign({}, state.userInfo, provider);
      uni.setStorageSync("USER_INFO", state.userInfo);
    },
    changLoginInfo(state, provider) {
      state.loginInfo = Object.assign({}, state.loginInfo, provider);
      uni.setStorage({
        key: 'LOGIN_USER_INFO',
        data: state.loginInfo
      });
    },
  },
  actions: {
    getUserInfo({ state, commit }, params) {
      return $api.getWxUserInfo(params).then((res) => {
        if (res.code == 200) {
          commit("changUserInfo", res.data);
          return res.data;
        }
      });
    },
    refreshToken({ state, commit }) {
      $api.refreshToken().then((res) => {
        if (res.code == 200) {
          commit("changToken", res.data.access_token);
        }
      });
    },
    refreshBalance({ state, commit }) {
      return $api.getBalance().then((res) => {
        if (res.code == 200) {
          commit("changUserInfo", res.data);
        }
      });
    },
    wxCodeLogin({ state, commit }) {
      return new Promise(function (resolve, reject) {
        wx.login({
          success: (r) => {
            return $api.onWxLogin({ code: r.code }).then((res) => {
              if (res.code == 200) {
                let { access_token, user_third } = res.data;
                commit("changToken", access_token.access_token);
                commit("changLoginInfo", user_third);
                resolve(res)
              }
            });
          },
        });
      })
    },
    loggedinUserInfo({ state, commit }) {
      $api.loggedinUserInfo().then((res) => {
        if (res.code == 200) {
          commit("changUserInfo", res.data);
        }
      });
    }
  },
});
export default store;
